﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;
//using StoreClientModule;
using UnityCore;
using UploadManager;
using System.Drawing.Printing;

namespace MBBStoreClient
{
    public partial class frmPurchaseOrderManager : Form
    {
        SynchronizeData sync = new SynchronizeData();
        UnityScriptEngine.Threader t = new UnityScriptEngine.Threader();

        readDetails path = new readDetails();
        readDetails pLD = new readDetails();
        priceDetails pD = new priceDetails();

        DataTable exportPurchaseOrder = new DataTable();
        DataTable exportPurchaseOrderItems = new DataTable();
        DataTable exportPurchasePayments = new DataTable();
        DataTable exportSupplierProfile = new DataTable();
        DataTable tmp = new DataTable();
        DataTable extractedPO = new DataTable();
        DataRow[] arr = new DataRow[0];
        double paymentGrandTotal = 0;

        public frmPurchaseOrderManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }

        private void InitializeForm()
        {
            sync.ProcessCompleted += new CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new CoreHandler(sync_ProcessError);
            sync.Stores();

            path.fileNames = new List<string>();
            pD.tables = new List<DataTable>();
            btnSearch.Click += new EventHandler(btnSearch_Click);
            txtFilter.SelectedIndex = 0;
            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            txtSearch.Focus();
            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            t.MethodCompleted += new EventHandler(delegate(object sender, EventArgs e)
            {
                t.SafeCall(this, delegate
                {
                    switch (sender.ToString())
                    {
                        case "generateResult":

                            grdItems.DataSource = tmp;
                            FormatGrid();
                            pnlMsg.Visible = false;
                            break;
                    }
                });
            });
        }

        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            btnSearch_Click(null, null);
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            //extract data
            path.date = "";
            path.remNode = cmbStore.Text;
            path.fileNames.Clear();
            path.fileNames.Add("tblpurchaseorder");
            path.fileNames.Add("tblpurchaseorderitems");
            path.fileNames.Add("tblpurchaseorderpayments");
            path.fileNames.Add("tblsupplierprofile");
            sync.ReadMany(path);
            pnlMsg.Visible = true;

            
        }

        void query()
        {
            arr = new DataRow[0];
            if (cmbStore.Text != "")
            {
                switch (txtFilter.Text)
                {
                    case "All":
                        arr = extractedPO.Select("[P.O. Number] LIKE '%" + txtSearch.Text + "%' OR Supplier LIKE '%" + txtSearch.Text + "%'" +
                            " OR [P.O. Date] LIKE '%" + txtSearch.Text + "%' OR [Payment Terms] LIKE '%" + txtSearch.Text + "%'"
                            );
                        
                        break;
                    case "With Payments":
                        arr = extractedPO.Select("(NOT[Total Payments] = '0.00') AND ([P.O. Number] LIKE '%" + txtSearch.Text + "%' OR Supplier LIKE '%" + txtSearch.Text + "%'" +
                            " OR [P.O. Date] LIKE '%" + txtSearch.Text + "%' OR [Payment Terms] LIKE '%" + txtSearch.Text + "%')"
                            );
                        break;
                    case "Without Payments":
                        arr = extractedPO.Select("([Total Payments] = '0.00') AND ([P.O. Number] LIKE '%" + txtSearch.Text + "%' OR Supplier LIKE '%" + txtSearch.Text + "%'" +
                            " OR [P.O. Date] LIKE '%" + txtSearch.Text + "%' OR [Payment Terms] LIKE '%" + txtSearch.Text + "%')"
                            );
                        break;
                    default:
                        break;
                }
                t.MethodCall(generateResult);
            }
        }
        void generateResult()
        {
            tmp = extractedPO.Clone();
            for (int i = 0; i < arr.Length; i++)
                tmp.ImportRow(arr[i]);

            
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
                pnlMsg.Visible = false;
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        cmbStore.SelectedIndex = 0;
                        //extract data
                        
                        break;
                    case "ReadMany":
                        exportPurchaseOrder = sync.exportTables[0];
                        exportPurchaseOrderItems = sync.exportTables[1];
                        exportPurchasePayments = sync.exportTables[2];
                        exportSupplierProfile = sync.exportTables[3];
                        if (exportPurchaseOrder.Rows.Count > 0)
                        {
                            extractedPO = CreateDataTable(exportPurchaseOrder, exportSupplierProfile, exportPurchasePayments, exportPurchaseOrderItems);
                            query();
                        }
                        else
                        {
                            arr = new DataRow[0];
                            t.MethodCall(generateResult);
                            pnlMsg.Visible = false;
                        }
                        break;
                }
            });
        }

        DataTable CreateDataTable(DataTable tblPO, DataTable tblSP, DataTable tblPayments, DataTable tblPOI)
        {
            
            DataTable dt = new DataTable();
            dt.Columns.Add("P.O. Number");
            dt.Columns.Add("Supplier");
            dt.Columns.Add("P.O. Date");
            dt.Columns.Add("Payment Terms");
            dt.Columns.Add("Total Amount");
            dt.Columns.Add("Total Payments");
            dt.Columns.Add("Balance");

            for (int i = 0; i < tblPO.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();

                string poNumber = tblPO.Rows[i]["fNumber"].ToString();
                dr[0] = tblPO.Rows[i]["fNumber"].ToString();
                //get supplier name
                string fRefNum = tblPO.Rows[i]["fRefNum"].ToString();
                for (int j = 0; j < tblSP.Rows.Count; j++)
                {
                    if (fRefNum.Equals(tblSP.Rows[j]["fRefNum"].ToString()))
                    {
                        dr[1] = tblSP.Rows[j]["fName"].ToString();
                        j = tblSP.Rows.Count;
                    }
                }
                     
                dr[2] = tblPO.Rows[i]["fDate"].ToString();
                dr[3] = tblPO.Rows[i]["fTerms"].ToString();
                
                //get total amount 
                double qty, price, amount=0, totalAmount=0;
                for (int x = 0; x < tblPOI.Rows.Count; x++)
                {
                    if (poNumber.Equals(tblPOI.Rows[x]["fNumber"].ToString()))
                    {
                        qty = double.Parse(tblPOI.Rows[x]["fQty"].ToString());
                        price = double.Parse(tblPOI.Rows[x]["fPrice"].ToString());
                        amount = qty * price;
                        totalAmount += amount;
                    }
                    
                }
                dr[4] = Common.FormatCurrency(totalAmount);
                //get total payment made
                double subTotal = 0, grandTotal = 0;
                for (int z = 0; z < tblPayments.Rows.Count; z++)
                {
                    if (poNumber.Equals(tblPayments.Rows[z]["fNumber"].ToString()))
                    {
                        subTotal = double.Parse(tblPayments.Rows[z]["fPaymentAmount"].ToString());
                        grandTotal += subTotal;
                    }
                }
                dr[5] = Common.FormatCurrency(grandTotal);
                double bal = totalAmount - grandTotal;
                dr[6] = Common.FormatCurrency(bal);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        void FormatGrid()
        {
            if (grdItems.Rows.Count > 0)
            {
                grdItems.Columns[0].Width = (grdItems.Width * 10) / 100;
                grdItems.Columns[1].Width = (grdItems.Width * 30) / 100;
                grdItems.Columns[2].Width = (grdItems.Width * 10) / 100;
                grdItems.Columns[3].Width = (grdItems.Width * 10) / 100;
                grdItems.Columns[4].Width = (grdItems.Width * 12) / 100;
                grdItems.Columns[5].Width = (grdItems.Width * 12) / 100;
                grdItems.Columns[6].Width = (grdItems.Width * 12) / 100;

                grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                grdItems.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                grdItems.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                grdItems.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                if (grdItems.Rows.Count > 0)
                {
                    for (int i = 0; i < grdItems.Rows.Count; i++)
                    {
                        grdItems.Rows[i].Cells[2].Value = grdItems.Rows[i].Cells[2].Value.ToString().Split(' ')[0];
                    }
                }
            }
        }

        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count > 0)
            {
                Common.parent.ViewPO(grdItems.Rows[grdItems.SelectedRows[0].Index].Cells[0].Value.ToString(), cmbStore.Text);
            }
        }

        //printing
        int cnt = 0;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 150;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Courier New", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(cmbStore.Text, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString(Common.lStoreAddress, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 70, sf);

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Purchase Order Summary - Page " + pp, cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(DateTime.Now.ToString(), cFont, Brushes.Black, rm + 100, y, sf);
            //Column Header
            y += ht;
            y += ht;

            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm + 100, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm + 100, ht);
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 10) / 100);
            float tx = lm + (((rm - lm) * 5f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("P.O. #", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 35) / 100;
            tx = cx - ((rm - lm) * 35) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Supplier Name", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 15) / 100;
            tx = cx - ((rm - lm) * 15) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Date", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Total Amount", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Total Payment", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 20) / 100;
            e.Graphics.DrawString("Balance", cFont, Brushes.Black, tx, y, sf);
            //Data
            y += ht * (1.5f);
            cFont = new Font("Courier New", 10f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0;

            while (cl <= lpp && cnt < grdItems.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 1;
                string str = grdItems.Rows[cnt].Cells[0].Value.ToString();
                if (str.Length > 10)
                {
                    str = str.Substring(0, 7) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);


                stx += ((rm - lm) * 11) / 100;
                str = grdItems.Rows[cnt].Cells[1].Value.ToString();
                if (str.Length > 23)
                {
                    str = str.Substring(0, 20) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 34) / 100;
                str = grdItems.Rows[cnt].Cells[2].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 33) / 100;
                sf.Alignment = StringAlignment.Far;
                str = grdItems.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 21) / 100;
                str = grdItems.Rows[cnt].Cells[5].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 17) / 100;
                str = grdItems.Rows[cnt].Cells[6].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                y += ht;
                cnt++;
                cl++;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdItems.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 1;
                pp = 1;
            }
        }
    }
}
